package com.example.choupaiapp.main.activity.publish;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.bean.FollowFansBean;
import com.example.choupaiapp.main.bean.SearchResultBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.bean.UserModelListBean;
import com.example.choupaiapp.main.constant.Url;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2020/2/27.
 */

public class UserListActivity extends CommonActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.search_et)
    EditText searchEt;
    @BindView(R.id.clear)
    ImageView clear;
    @BindView(R.id.listview)
    ListView listView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.empty_img)
    ImageView empty_img;
    private int pageNum = 1;
    private int pageSize = 20;
    private UserInfoBean mUserInfoBean;
    private QuickAdapter<FollowFansBean.PageBean.ListBean> quickAdapter;
    private int userFlag = 0;
    private UserModelListBean userModelListBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_list);
    }

    @Override
    protected void initView() {
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            userModelListBean = (UserModelListBean) bundle.getSerializable("userModels");
        }

        mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");

        quickAdapter = new QuickAdapter<FollowFansBean.PageBean.ListBean>(context, R.layout.item_user_list) {
            @Override
            protected void convert(BaseAdapterHelper helper, FollowFansBean.PageBean.ListBean item) {
                helper.setText(R.id.name, item.getNickname());
            }
        };

        listView.setAdapter(quickAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (userModelListBean != null) {
                    for (int j = 0; j < userModelListBean.getUserModels().size(); j++) {
                        if (userModelListBean.getUserModels().get(j).getUser_id().equals(quickAdapter.getItem(i).getByUserId()+"")) {
                            showImageToas("该联系人已选择");
                            return;
                        }
                    }
                }

                EventBus.getDefault().post("pubish_@_user:" + quickAdapter.getItem(i).getNickname() + ":" + quickAdapter.getItem(i).getByUserId());
                finishActivity();

            }
        });

        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().length() > 0) {
                    clear.setVisibility(View.VISIBLE);
                    pageNum = 1;
                    requestSearchData();
                } else {
                    clear.setVisibility(View.INVISIBLE);
                }
            }
        });

        searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索的时候隐藏软键盘
                    InputMethodManager manager = (InputMethodManager) searchEt.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    manager.hideSoftInputFromWindow(searchEt.getWindowToken(), 0);
                    // 在这里写搜索的操作,一般都是网络请求数据

                    pageNum = 1;
                    requestSearchData();
                    return true;
                }

                return false;
            }
        });
    }

    private void requestSearchData() {
        userFlag = 1;
        showDialog(context, null);
        HttpParams params = new HttpParams();
        params.put("type", 1);
        params.put("search", searchEt.getText().toString().trim());
        params.put("limit", pageSize);
        params.put("page", pageNum++);
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.SEARCH_RESULT, params, Url.SEARCH_RESULT, new Callback<SearchResultBean>() {
            @Override
            public void onSuccess(SearchResultBean searchResultBean) {
                dismissDialog();
                if (searchResultBean.getCode() == Contacts.SUCCESS) {
                    if (pageNum - 1 == 1) {
                        if (searchResultBean.getUserPage().getList() == null || searchResultBean.getUserPage().getList().size() == 0) {
                            empty_img.setVisibility(View.VISIBLE);
                            empty_img.setImageResource(R.mipmap.icon_no_follow);
                        } else {
                            empty_img.setVisibility(View.GONE);
                        }
                        quickAdapter.clear();
                        for (int i = 0; i < searchResultBean.getUserPage().getList().size(); i++) {
                            FollowFansBean.PageBean.ListBean listBean = new FollowFansBean.PageBean.ListBean();
                            listBean.setNickname(searchResultBean.getUserPage().getList().get(i).getNickname());
                            listBean.setByUserId(searchResultBean.getUserPage().getList().get(i).getUserId());
                            quickAdapter.add(listBean);
                        }
                    } else {
                        for (int i = 0; i < searchResultBean.getUserPage().getList().size(); i++) {
                            FollowFansBean.PageBean.ListBean listBean = new FollowFansBean.PageBean.ListBean();
                            listBean.setNickname(searchResultBean.getUserPage().getList().get(i).getNickname());
                            listBean.setByUserId(searchResultBean.getUserPage().getList().get(i).getUserId());
                            quickAdapter.add(listBean);
                        }
                    }
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    quickAdapter.notifyDataSetChanged();

                    int pagecount;
                    if (searchResultBean.getUserPage().getTotalCount() % pageSize == 0) {
                        pagecount = searchResultBean.getUserPage().getTotalCount() / pageSize;
                    } else {
                        pagecount = searchResultBean.getUserPage().getTotalCount() / pageSize + 1;
                    }

                    if (pageNum > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }
                } else {
                    if (searchResultBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        if (pageNum - 1 == 1) {
                            empty_img.setVisibility(View.VISIBLE);
                            empty_img.setImageResource(R.mipmap.icon_no_net);
                        }
                        showImageToas(searchResultBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
                if (pageNum - 1 == 1) {
                    empty_img.setVisibility(View.VISIBLE);
                    empty_img.setImageResource(R.mipmap.icon_no_net);
                }
            }
        });
    }

    @Override
    protected void initData() {
        userFlag = 0;
        showDialog(context, null);
        HttpParams params = new HttpParams();
        params.put("userId", mUserInfoBean.getUser().getUserId());
        params.put("type", 1);
        params.put("loginUserId", mUserInfoBean.getUser().getUserId());
        params.put("limit", pageSize);
        params.put("page", pageNum++);
        finalOkGo.request(RequestType.POST, Url.WATCH_USER_FOLLOW_LIST, params, Url.WATCH_USER_FOLLOW_LIST, new Callback<FollowFansBean>() {
            @Override
            public void onSuccess(FollowFansBean followFansBean) {
                dismissDialog();
                if (followFansBean.getCode() == Contacts.SUCCESS) {
                    if (pageNum - 1 == 1) {
                        if (followFansBean.getPage().getList() == null || followFansBean.getPage().getList().size() == 0) {
                            empty_img.setVisibility(View.VISIBLE);
                            empty_img.setImageResource(R.mipmap.icon_no_follow);
                        } else {
                            empty_img.setVisibility(View.GONE);
                        }
                        quickAdapter.clear();
                        quickAdapter.addAll(followFansBean.getPage().getList());
                    } else {
                        quickAdapter.addAll(followFansBean.getPage().getList());
                    }

                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    quickAdapter.notifyDataSetChanged();

                    int pagecount;
                    if (followFansBean.getPage().getTotalCount() % pageSize == 0) {
                        pagecount = followFansBean.getPage().getTotalCount() / pageSize;
                    } else {
                        pagecount = followFansBean.getPage().getTotalCount() / pageSize + 1;
                    }

                    if (pageNum > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }
                } else {
                    if (followFansBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        if (pageNum - 1 == 1) {
                            empty_img.setVisibility(View.VISIBLE);
                            empty_img.setImageResource(R.mipmap.icon_no_net);
                        }
                        showImageToas(followFansBean.getMsg());
                    }
                }

            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
                if (pageNum - 1 == 1) {
                    empty_img.setVisibility(View.VISIBLE);
                    empty_img.setImageResource(R.mipmap.icon_no_net);
                }
            }
        });
    }

//    @Override
    @OnClick({R.id.clear, R.id.cancel})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.clear:
                searchEt.setText("");
                break;
            case R.id.cancel:
                finishActivity();
                break;
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if (userFlag == 0) {
            initData();
        } else {
            requestSearchData();
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        if (userFlag == 0) {
            pageNum = 1;
            initData();
        } else {
            pageNum = 1;
            requestSearchData();
        }

    }
}
